package com.example.springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springboot.common.Constants;
import com.example.springboot.entity.Message;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.MessageMapper;
import com.example.springboot.service.IMessageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.utils.TimeUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements IMessageService {

    @Override
    public List<Message> getByUser(Integer userId) {
        if (userId == null)
            throw new ServiceException(Constants.CODE_600,"系统错误");
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        List<Message> messageList = list(queryWrapper);
        if (messageList == null)
            return null;
        messageList.sort(Comparator.comparing(Message::getCreateTime).reversed());
        List<Message> result = new ArrayList<>();
        List<Message> read = new ArrayList<>();
        for (Message message : messageList) {
            message.setRelativeTime(TimeUtil.createRelative(message.getCreateTime()));
            if (message.getStatement().equals("未读"))
                result.add(message);
            else
                read.add(message);
        }
        result.addAll(read);
        return result;
    }

}
